package cn.qingyun.gis.modules.init.system.sso.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.init.system.service.ISysUserService;
import cn.qingyun.gis.modules.init.system.sso.crm.CrmAuthItem;
import cn.qingyun.gis.modules.init.system.vo.LoginUser;
import cn.qingyun.gis.modules.init.utils.SystemUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
@Slf4j
public class CrmTool {
    private static final Integer RES_CODE_SUCCESS = 0;
    private static String authUrl;
    private static String activeProfile;
    private static ISysUserService iSysUserService;

    /**
     * 获取权限网格列表
     *
     * @param crmAccount
     * @return
     */
    public static List<CrmAuthItem> authGrigList(String crmAccount) {
        List<CrmAuthItem> authItems = Lists.newArrayList();
        if ("prod".equals(activeProfile)||"test".equals(activeProfile)) {
            try {
                Map<String, Object> params = Maps.newHashMap();
                params.put("type", 3);
                params.put("crmAccount", crmAccount);
                HttpRequest httpRequest = HttpUtil.createPost(authUrl).body(JSONUtil.toJsonStr(params))
                        .timeout(1000)
                        .header("Content-Type", "application/json");

                HttpResponse response = httpRequest.execute();
                log.debug("获取权限网格 {} 参数 {} 结果 {}", authUrl, params, response.body());
                if (response.isOk()) {
                    log.debug("获取权限网格 {} 参数 {} 结果 {}", authUrl, params, response.body());

                    JSONObject parseObj = JSONUtil.parseObj(response.body());

                    if (RES_CODE_SUCCESS.equals(parseObj.getByPath("res_code", Integer.class))) {
                        for (Object o : parseObj.getJSONArray("result")) {
                            JSONObject entries = (JSONObject) o;

                            authItems.add(entries.toBean(CrmAuthItem.class));
                        }
                    }

                    if (CollUtil.isEmpty(authItems)) {
                        throw new CommonException("根据工号获取权限网格失败, 请联系管理员");
                    }
                }

                // 去重逻辑
                Map<String, CrmAuthItem> uniqMap = Maps.newHashMap();
                for (CrmAuthItem authItem : authItems) {
                    uniqMap.put(authItem.getAreaCode(), authItem);
                }
                return new ArrayList<>(uniqMap.values());
            } catch (Exception e) {
                log.error("根据工号获取权限网格失败, 请联系管理员", e);
                throw new CommonException("根据工号获取权限网格失败, 请联系管理员");
            }
        }else if ("local".equals(activeProfile)){
            CrmAuthItem crmAuthItem = new CrmAuthItem();
            crmAuthItem.setAreaCode("SD");
            crmAuthItem.setAreaName("山东");
            crmAuthItem.setAllParentCode("SD");
            crmAuthItem.setFullName("山东");
            authItems.add(crmAuthItem);
        }

        return authItems;
    }

    @Value("${qingyun.grid.service-host:http://134.80.208.184}")
    public void setHwGridHost(String authUrl) {
        CrmTool.authUrl = String.format("%s:55501/SDCommon/v1/nk/producer/grid/list", authUrl);
    }

    public static List<CrmAuthItem> getCrmGridAuth() {
        LoginUser currentUser = SystemUtil.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            throw new CommonException("解析用户失败");
        }
        return authGrigList(currentUser.getWorkNo());
    }

    @Value("${spring.profiles.active:test}")
    public void setActiveProfile(String activeProfile) {
        CrmTool.activeProfile = activeProfile;
    }

    @Resource
    public void setiSysUserService(ISysUserService iSysUserService) {
        CrmTool.iSysUserService = iSysUserService;
    }

    /**
     * 查询最高级别权限
     *
     * @return
     */
    public static CrmAuthItem getMaxCrmGridAuth() {
        List<CrmAuthItem> crmGridAuth = getCrmGridAuth();
        if(CollUtil.isEmpty(crmGridAuth)){
            throw new CommonException("未查询到当前用户权限信息");
        }

        CrmAuthItem minItem = crmGridAuth.get(0);  // 假设第一个项为最少层级项
        int minLevels = countDotLevels(minItem.getAreaCode());

        for (CrmAuthItem item : crmGridAuth) {
            int currentLevels = countDotLevels(item.getAreaCode());
            if (currentLevels < minLevels) {
                minItem = item;
                minLevels = currentLevels;
            }
        }
        return minItem;
    }

    // 计算 areaCode 中的层级数（即 '.' 的个数）
    public static int countDotLevels(String areaCode) {
        return areaCode.split("\\.").length - 1;  // 计算 '.' 的个数
    }

}
